//
//  APPhotosManager.swift
//  APSwift
//
//  Created by jianbo.pei on 2023/8/4.
//

import Foundation
import Photos

open class APPhotosManager {
    public required init() {}
    public static let shared = APPhotosManager()
}

extension APPhotosManager {
//    public func save(image: UIImage, )
}

extension APPhotosManager {
    /// 根据相薄名获取对应的相薄对象（如果未获取到，会创建）
    /// - Parameters:
    ///   - name: 相薄名
    ///   - debugEnable: 是否开启debug，开启会打印相关参数
    /// - Returns: 相薄对象
    public func fetchAlbum(by name: String, debugEnable: Bool = false) -> PHAssetCollection? {
        /// 1、先判断是否存在对应的自定义相册
        let collections = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: nil)
        var collection: PHAssetCollection? = nil
        collections.enumerateObjects { ac, _, stop in
            if let lt = ac.localizedTitle, lt == name {
                collection = ac
                stop.initialize(to: (true as ObjCBool))
            }
        }
        if let collection = collection {
            return collection
        }
        
        /// 2、如果没有，就新建一个相册
        var collectionId: String?
        PHPhotoLibrary.shared().performChanges {
            collectionId = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: name).placeholderForCreatedAssetCollection.localIdentifier
        } completionHandler: { suc, _ in
            
        }
        guard let collectionId = collectionId, !collectionId.isEmpty else { return nil }
        return PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [collectionId], options: nil).lastObject
    }
}

